#!/usr/bin/python3

import sys
# Avoid creating archive-process-emailc
if hasattr(sys, "dont_write_bytecode"):
    sys.dont_write_bytecode = True

import imp
import unittest
import os
import django
import io

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nm2.settings_tapi")
django.setup()

import backend.models as bmodels

Dispatcher = imp.load_source("ape", "./archive-process-email").Dispatcher

class TestLookup(unittest.TestCase):
    def setUp(self):
        # Get an active process with an AM and a uid
        self.proc = bmodels.Process.objects.filter(manager__isnull=False, person__uid__isnull=False, is_active=True)[0]

    def make_email(self, dk=None, src="am", dst="nm"):
        """
        src and dst can be "am", "nm", "fd", or a list of Person objects
        """
        from email.mime.text import MIMEText
        from email.utils import formataddr

        def get_addr(t):
            if t == "am":
                return formataddr((self.proc.manager.person.fullname, self.proc.manager.person.uid + "@debian.org"))
            elif t == "nm":
                return formataddr((self.proc.person.fullname, self.proc.person.email))
            elif t == "fd":
                return "Enrico Zini <enrico@enricozini.org>"
            elif isinstance(t, list):
                return ", ".join(formataddr((p.fullname, p.email)) for p in t)
            else:
                raise KeyError("Invalid actor: '%s'" % t)

        res = MIMEText("body", _charset="utf-8")
        res["From"] = get_addr(src)
        res["To"] = get_addr(dst)
        res["Subject"] = "Test mail"
        if dk is not None:
            res["Delivered-To"] = "archive-%s@nm.debian.org" % dk
        else:
            res["Delivered-To"] = "archive@nm.debian.org"
        return res.as_string().encode("utf-8")

    def make_dispatcher(self, **kw):
        return Dispatcher(io.BytesIO(self.make_email(**kw)))

    def testDestkeyEmail(self):
        dest = self.proc.person.email.replace("@", "=")
        d = self.make_dispatcher(dk=dest)
        key = d.get_dest_key()
        self.assertEqual(key, dest)
        arc_key = d.archive_key_from_dest_key(key)
        self.assertEqual(arc_key, self.proc.archive_key)

    def testDestkeyUid(self):
        dest = self.proc.person.uid
        d = self.make_dispatcher(dk=dest)
        key = d.get_dest_key()
        self.assertEqual(key, dest)
        arc_key = d.archive_key_from_dest_key(key)
        self.assertEqual(arc_key, self.proc.archive_key)

if __name__ == '__main__':
    unittest.main()
